﻿using System;
using System.Diagnostics;
using System.Web;
using Microsoft.SharePoint;

namespace CKS.EBE.API
{
	/// <summary>
	/// get a SPWeb which is created with the current users context
	/// </summary>
	class UserWeb : IDisposable
	{
		private readonly SPSite _Site;
		private readonly SPWeb _Web;
		private bool _DisposeRequired;

		public SPWeb Web
		{
			get { return _Web; }
		}

		public UserWeb()
		{
			if (SPContext.Current.Web.CurrentUser != null)
			{
				// a user is logged on
				_Site = SPContext.Current.Site;
				_Web = SPContext.Current.Web;
				_DisposeRequired = false;
				return;
			}

			if (HttpContext.Current.Request.IsAuthenticated)
			{
				// need to create objects under the usercontext
				SPUser user = null;
				SPSecurity.RunWithElevatedPrivileges(delegate { user = EnsureUser(); });
				_Site = new SPSite(SPContext.Current.Web.Url, user.UserToken);
				_Web = _Site.OpenWeb();
			}
		}

		/// <summary>
		/// connect to the web as application pool account to ensure the user
		/// </summary>
		/// <returns></returns>
		private SPUser EnsureUser()
		{
			SPUser user;
			using (var site = new SPSite(SPContext.Current.Web.Url))
			{
				var web = site.OpenWeb();
				try
				{
					web.AllowUnsafeUpdates = true;
					string loginName = HttpContext.Current.User.Identity.Name;
					Trace.Write(string.Format("Ensuring user {0} on web {1}", loginName, web.Url));
					user = web.EnsureUser(loginName);
					_DisposeRequired = true;
				}
				finally
				{
					web.AllowUnsafeUpdates = false;
				}
			}
			return user;
		}

		public void Dispose()
		{
			if (_DisposeRequired)
			{
				if (_Site != null) _Site.Dispose();
				// the web does not need to be disposed, if the site is
			}
		}
	}
}